﻿using ScottPlot.Colormaps;
using ScottPlot;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ScottPlot.WPF;
using System.Windows.Markup;
using Colors = ScottPlot.Colors;
using System.Collections.ObjectModel;
using ScottPlot.Plottables;
using SeuicScannerAPI;
using System.Threading;
using System.Windows.Threading;
using System.IO.Ports;
using System.Data.SqlClient;
using System.Data;

namespace WpfWeight
{
    /// <summary>
    /// WindowChaChe.xaml 的交互逻辑
    /// </summary>
    public partial class WindowChaChe : Window
    {
        static string conn = "server=192.168.1.21;uid=sa;pwd=aaar8001;database=aaarTest;Encrypt=True;TrustServerCertificate=True;";

        BackgroundWorker backgroundWorker    = new BackgroundWorker();
        Scanner scanner = new Scanner();
        public WindowChaChe()
        {
            InitializeComponent();
            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            var plt = WpfPlot1.Plot;
         
            plt.Axes.SetLimitsY(10, 5000);
            dgselected.ItemsSource = weight2Bilselected;

        }
        public ObservableCollection<ParaWeightModel> weight2Bilselected = new ObservableCollection<ParaWeightModel>();
        SerialPort port = new SerialPort("COM10");
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                List<DateTime> dtlist = new List<DateTime>();
                List<double> listdb = new List<double>();
                List<byte> bytes = new List<byte>(); if (!port.IsOpen)
                {
                    port.Open();
                    setlog("opened");
                }
                while (!backgroundWorker.CancellationPending)
                {

                    try
                    {



                      

                        port.DiscardInBuffer();
                        while (bytes.Count < 30 && !backgroundWorker.CancellationPending)
                        {

                            byte b = (byte)port.ReadByte();

                            bytes.Add(b);
                             
                        }
                         
                      
                        int start = bytes.IndexOf(bytes.First(t => t == 0x0D));
                        byte[] lastdata = bytes.ToArray().Skip(start + 1).Take(17).ToArray();

                  
                        var btsvalue = lastdata.Skip(4).Take(6).ToArray();
                        

 


                        double weightcom = (int.Parse(ASCIIEncoding.ASCII.GetString(btsvalue).ToString()) );


                        setlog("byte读重量:" + weightcom.ToString());
                        if (listdb.Count > 30)
                        {
                            listdb.RemoveAt(0);
                            dtlist.RemoveAt(0);
                        }
                        var weight = weightcom;
                        listdb.Add(weight);
                        dtlist.Add(DateTime.Now);
                        this.Dispatcher.Invoke(new Action(() =>
                        {
                            try
                            {



                                tbWeight.Text = weight.ToString();


                                WpfPlot1.Plot.Clear();
                                var plt = WpfPlot1.Plot;

                                plt.Axes.DateTimeTicksBottom();

                              
                                double maxd = 20;
                                if (listdb.Max() > maxd)
                                {
                                    maxd = listdb.Max() + 10;
                                }
                                plt.Axes.SetLimitsY(-10, maxd);

                                WpfPlot1.Plot.Add.Scatter(dtlist, listdb, ScottPlot.Colors.Red);

                                WpfPlot1.Refresh();
                                setlog(System.DateTime.Now.ToShortTimeString() + "读重量:" + weight.ToString());



                            }
                            catch (Exception ex2) { setlog(ex2.ToString()); }
                        }));

                        System.Threading.Thread.Sleep(300);
                    }
                    catch (Exception ex)
                    {
                        setlog(ex.ToString());
                        break;
                    }
                  

                    setlog("Received data:  end ");

                }
                setlog("结束台作业");

                this.Dispatcher.Invoke(new Action(() =>
                {
                    try
                    {



                        tbWeight.Text = "0";






                    }
                    catch (Exception ex2) { setlog(ex2.ToString()); }
                }));



                if (port.IsOpen)
                {
                    port.Close();
                    setlog("Close");
                }

            }
            catch (Exception ex)
            {
                setlog(ex.ToString());
            }
        }
        void setlog(string msg)
        {
           
                logtxt.Dispatcher.Invoke(new Action(() => {
                try
                {
                    logtxt.Text = logtxt.Text + "\r\n";
                    if (logtxt.Text.Length > 10000)
                    {
                        logtxt.Text = logtxt.Text.Substring(5000);


                    }
                    logtxt.Text = logtxt.Text + msg;
                    logtxt.ScrollToEnd();
                    }
                    catch { }
                }));
              
       
        }
        private void Buttonstart_Click(object sender, RoutedEventArgs e)
        {
            if (!backgroundWorker.IsBusy)
            { 
                backgroundWorker.RunWorkerAsync();
            }
        }

        private void Buttonend_Click(object sender, RoutedEventArgs e)
        {
            backgroundWorker.CancelAsync();
        }

        private void dgselected_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {

        }

        private void btnup_Click(object sender, RoutedEventArgs e)
        {
            if (tbWeight.Text == "0"   || string.IsNullOrEmpty(tbWeight.Text))
            { MessageBox.Show("秤通信不正常请重新连接"); return;  }
            try
            {
                if (MessageBox.Show("是否将" + tbbox.Text + "上传？"+ tbWeight.Text, "标题", MessageBoxButton.YesNo, MessageBoxImage.Information) != MessageBoxResult.Yes)
                { return; }
                backgroundWorker.CancelAsync();

                Post(new UpdateWeightModel { barcode = tbbox.Text, weight = double.Parse(tbWeight.Text) });
            }catch (Exception ex) { MessageBox.Show(ex.ToString()); }

        }
        public void Post( UpdateWeightModel value)
        {
            var myConnection = new SqlConnection(conn);

           
                //打开数据库
                myConnection.Open();
                //实例化命令对象
                SqlCommand myCommand = new SqlCommand();
                //把要操作的数据库传过来
                myCommand.Connection = myConnection;
                //操作类型为文本类型
                myCommand.CommandType = CommandType.Text;
                //
                myCommand.CommandText = @" update sfPackingListDetailLocation set weight = @weight where barcode = @barcode";
                myCommand.Parameters.Add(new SqlParameter("@barcode", value.barcode));
                myCommand.Parameters.Add(new SqlParameter("@weight", value.weight));

                //提交数据
                int ec = myCommand.ExecuteNonQuery();


                String sqlselelct = string.Format(" select    a.produceNo as  listno  , t.caseNum , t.weight from  sfPackingListDetailLocation t " +
                    " left join  sfPackingListMain a on t.mainID= a.pkid   where t.barcode  ='{0}'",
                    value.barcode);

                SqlCommand selectCommand = new SqlCommand();

                selectCommand.Connection = myConnection;
                selectCommand.CommandText = sqlselelct;
                selectCommand.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
                //创建DataSet对象
                DataSet ds = new DataSet();
                //将studentList这张表填充到DataSet数据集中
                sda.Fill(ds);

                //关闭数据库
                myConnection.Close();
            ParaWeightModel paraWeightModel = new ParaWeightModel();
            paraWeightModel.listno = ds.Tables[0].Rows[0]["listno"].ToString();
            paraWeightModel.caseNum = ds.Tables[0].Rows[0]["caseNum"].ToString();
            paraWeightModel.weight = ds.Tables[0].Rows[0]["weight"].ToString();
            weight2Bilselected.Insert(0, paraWeightModel);


        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {

               
                bool ret = scanner.InitScanner();
                if (ret == false)
                {
                    MessageBox.Show("初始化异常 InitScanner");
                }
                ret = scanner.ConnectScanner();
                if (ret == false)
                {
                    MessageBox.Show("连接异常 ConnectScanner");
                }
                else
                {
                    MessageBox.Show("初始化成功");
                }

                scanner.RecieveScanData += Scanner_RecieveScanData;
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }
        private void Scanner_RecieveScanData(string barcode)
        {
            this .Dispatcher .Invoke(new Action(() =>
            {
                //this.richTextBox1.AppendText(barcode + "\r\n");
                ////this.txtCodes.Text = allBarcodes;
                ////定位最新一行
                //this.richTextBox1.SelectionStart = this.richTextBox1.Text.Length; //this.txtCodes.Select(this.txtCodes.TextLength, 0);
                //this.richTextBox1.ScrollToCaret();

                ////大于1000行时，删除第一行。最大保留1000行的数据
                //if (this.richTextBox1.Lines.Length > 1000)
                //{
                //    this.richTextBox1.Lines = this.richTextBox1.Lines.Skip(1).ToArray();
                //}
                try
                {
                  
                    tbbox.Text = barcode;

                    tbwhbox.Text = "";
                    tbscbhbox.Text = "";

                    var myConnection = new SqlConnection(conn);


                        //打开数据库
                        myConnection.Open();


                        String sqlselelct = string.Format(" select    a.produceNo as  listno  , t.caseNum , t.weight from  sfPackingListDetailLocation t " +
                            " left join  sfPackingListMain a on t.mainID= a.pkid   where t.barcode  ='{0}'",
                            tbbox.Text.Trim());

                        SqlCommand selectCommand = new SqlCommand();

                        selectCommand.Connection = myConnection;
                        selectCommand.CommandText = sqlselelct;
                        selectCommand.CommandType = CommandType.Text;
                        SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
                        //创建DataSet对象
                        DataSet ds = new DataSet();
                        //将studentList这张表填充到DataSet数据集中
                        sda.Fill(ds);

                        //关闭数据库
                        myConnection.Close();
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        tbwhbox.Text = ds.Tables[0].Rows[0]["caseNum"].ToString();
                        tbscbhbox.Text = ds.Tables[0].Rows[0]["listno"].ToString();
                    }

                }
                catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            }));


        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            scanner.CloseScanner();
        }

        private void btnscan_Click(object sender, RoutedEventArgs e)
        {
            tbbox.Text = "";
            tbwhbox.Text = ""; 
            tbscbhbox.Text = "";
            if (!backgroundWorker.IsBusy)
            {
                backgroundWorker.RunWorkerAsync();
            }
           
            scanner.StartScan(ScanMode.Once);
        }

        private void btnendscan_Click(object sender, RoutedEventArgs e)
        {
            backgroundWorker.CancelAsync();
            scanner.StopScan();
        }

        private void tbbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //try { 
            //if (tbbox.Text.Trim().Length == Guid.NewGuid().ToString().Length) 
            //{

            //    var myConnection = new SqlConnection(conn);


            //    //打开数据库
            //    myConnection.Open();
                

            //    String sqlselelct = string.Format(" select    a.produceNo as  listno  , t.caseNum , t.weight from  sfPackingListDetailLocation t " +
            //        " left join  sfPackingListMain a on t.mainID= a.pkid   where t.barcode  ='{0}'",
            //        tbbox.Text.Trim());

            //    SqlCommand selectCommand = new SqlCommand();

            //    selectCommand.Connection = myConnection;
            //    selectCommand.CommandText = sqlselelct;
            //    selectCommand.CommandType = CommandType.Text;
            //    SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
            //    //创建DataSet对象
            //    DataSet ds = new DataSet();
            //    //将studentList这张表填充到DataSet数据集中
            //    sda.Fill(ds);

            //    //关闭数据库
            //    myConnection.Close();
                  
            //        tbwhbox.Text = ds.Tables[0].Rows[0]["caseNum"].ToString();
            //        tbscbhbox.Text = ds.Tables[0].Rows[0]["listno"].ToString();

            //    }
            //}
            //catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }

        private void btnendscanhand_Click(object sender, RoutedEventArgs e)
        {
            try {
                if (tbWeight.Text == "0" || string.IsNullOrEmpty(tbWeight.Text))
                { MessageBox.Show("秤通信不正常请重新连接"); return; }
                if (MessageBox.Show("是否将"+ tbscbhbox.Text.Trim()+"_" + tbwhbox.Text.Trim()+"上传？", "标题", MessageBoxButton.YesNo, MessageBoxImage.Information) != MessageBoxResult.Yes)
                { return; }
                    tbbox.Text = "";
                var myConnection = new SqlConnection(conn);


                //打开数据库
                myConnection.Open();
                //实例化命令对象
                SqlCommand myCommand = new SqlCommand();
                //把要操作的数据库传过来
                myCommand.Connection = myConnection;
                //操作类型为文本类型
                myCommand.CommandType = CommandType.Text;
                //
                myCommand.CommandText = @"  update  t set t.weight = @weight from sfPackingListDetailLocation t left  join  sfPackingListMain a on t.mainID= a.pkid where    t.caseNum =  @caseNum and  a.produceNo = @produceNo";
                myCommand.Parameters.Add(new SqlParameter("@produceNo", tbscbhbox.Text.Trim()));
                myCommand.Parameters.Add(new SqlParameter("@caseNum", tbwhbox.Text.Trim()));
                myCommand.Parameters.Add(new SqlParameter("@weight", int.Parse(tbWeight.Text)));
                //提交数据
                int ec = myCommand.ExecuteNonQuery();


                String sqlselelct = " select   a.produceNo as  listno  , t.caseNum , t.weight  from sfPackingListDetailLocation t left  join  sfPackingListMain a on t.mainID= a.pkid where    t.caseNum =  @caseNum and  a.produceNo = @produceNo";
                SqlCommand selectCommand = new SqlCommand();
                selectCommand.Parameters.Add(new SqlParameter("@produceNo", tbscbhbox.Text.Trim()));
                selectCommand.Parameters.Add(new SqlParameter("@caseNum", tbwhbox.Text.Trim()));

                selectCommand.Connection = myConnection;
                selectCommand.CommandText = sqlselelct;
                selectCommand.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(selectCommand);
                //创建DataSet对象
                DataSet ds = new DataSet();
                //将studentList这张表填充到DataSet数据集中
                sda.Fill(ds);

                //关闭数据库
                myConnection.Close();
                ParaWeightModel paraWeightModel = new ParaWeightModel();
                paraWeightModel.listno = ds.Tables[0].Rows[0]["listno"].ToString();
                paraWeightModel.caseNum = ds.Tables[0].Rows[0]["caseNum"].ToString();
                paraWeightModel.weight = ds.Tables[0].Rows[0]["weight"].ToString();
                weight2Bilselected.Insert(0, paraWeightModel);
            } catch (Exception ex)
            { MessageBox.Show(ex.ToString()); }
        }
    }
    public class UpdateWeightModel
    {
        public String barcode { get; set; }
        public double weight { get; set; }
    }
    public class ParaWeightModel
    {
        public String listno { get; set; }

        public String caseNum { get; set; }
        public String weight { get; set; }
    }
}
